package com.tinyengine.it.service.engine.extend.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tinyengine.it.mapper.TPageMapper;
import com.tinyengine.it.model.entity.TPage;
import com.tinyengine.it.service.engine.extend.TPageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Entities;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Administrator
 * @description 针对表【t_page(页面表)】的数据库操作Service实现
 * @createDate 2025-03-27 15:52:11
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class TPageServiceImpl extends ServiceImpl<TPageMapper, TPage> implements TPageService {

    private final TPageMapper tPageMapper;

    @Override
    public String generationSfcContent(String sfc) {
        if (StrUtil.isBlank(sfc)) {
            return null;
        }

        String content = "";

        try {
            Pattern pattern = Pattern.compile("(?s)<template>(.*?)</template>");
            Matcher matcher = pattern.matcher(sfc);
            if (matcher.find()) {
                String templateContent = matcher.group(1);

                // Jsoup 解析并格式化 HTML 内容
                Document doc = Jsoup.parse(templateContent);
                doc.outputSettings()
                        .indentAmount(2)                 // 缩进空格数，默认 1
                        .prettyPrint(true)               // 是否启用格式化缩进
                        .outline(false)                  // 是否使用 outline 模式（不缩进嵌套块）
                        .syntax(Document.OutputSettings.Syntax.html) // 选择 html 或 xml
                        .escapeMode(Entities.EscapeMode.xhtml); // 转义策略

                doc.outputSettings()
                        .indentAmount(2)
                        .prettyPrint(true)
                        .escapeMode(Entities.EscapeMode.xhtml);

                Element body = doc.body();
                String formattedTemplate = "<template>\n" +
                        body.html().stripTrailing() + "\n</template>";

                // 替换原始 <template> 区域
                content = matcher.replaceFirst(Matcher.quoteReplacement(formattedTemplate));
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return content;
    }

    @Override
    public String getPath(Integer id, Boolean mySelf) {
        String dirInfo = baseMapper.getDirInfo(id, mySelf);
        return Optional.ofNullable(dirInfo).orElse("");
    }
}




